package podman

import (
	"context"
	"fmt"
	"github.com/containers/podman/v5/pkg/bindings/containers"
	"github.com/containers/podman/v5/pkg/specgen"
	"io"
	"net/http"
	"os"
	"path/filepath"

	"github.com/containers/podman/v5/pkg/bindings"
	"github.com/rs/zerolog/log"
)

type Client struct {
	conn context.Context
}

func New() (*Client, error) {
	sockDir := os.Getenv("XDG_RUNTIME_DIR")
	dbus := os.Getenv("DBUS_SESSION_BUS_ADDRESS")

	if sockDir == "" {
		return nil, fmt.Errorf("XDG_RUNTIME_DIR not set")
	}
	if dbus == "" {
		return nil, fmt.Errorf("DBUS_SESSION_BUS_ADDRESS not set")
	}
	socketPath := "unix:" + filepath.Join(sockDir, "podman", "podman.sock")
	ctx, err := bindings.NewConnection(context.Background(), socketPath)
	if err != nil {
		log.Error().Err(err).Msg("connect to podman socket failed")
		return nil, fmt.Errorf("failed to connect: %w", err)
	}

	return &Client{conn: ctx}, nil
}

func (c *Client) getClient() (*bindings.Connection, error) {
	return bindings.GetClient(c.conn)
}
func (c *Client) doRequest(rb *RequestBuilder) (*bindings.APIResponse, error) {
	connection, err := bindings.GetClient(c.conn)
	if err != nil {
		return nil, fmt.Errorf("get client failed: %w", err)
	}
	return rb.Send(connection)
}
func (c *Client) PodmanInfo() (string, error) {
	rb := NewGetRequest("/info").
		WithBody(nil).
		WithQueries(nil).
		WithHeaderContentType("application/json")
	apiResp, err := c.doRequest(rb)
	if err != nil {
		return "", fmt.Errorf("request failed: %w", err)
	}
	defer apiResp.Body.Close()

	if apiResp.StatusCode != http.StatusOK {
		body, _ := io.ReadAll(apiResp.Body)
		return "", fmt.Errorf("status %d, body: %s", apiResp.StatusCode, body)
	}

	body, err := io.ReadAll(apiResp.Body)
	if err != nil {
		return "", fmt.Errorf("read body failed: %w", err)
	}

	return string(body), nil
}

func (c *Client) CreateUbuntuContainer() { //Test
	testImage := "docker.io/library/ubuntu:22.04"
	s := specgen.NewSpecGenerator(testImage, false)
	resp, err := containers.CreateWithSpec(c.conn, s, nil)
	if err != nil {
		return
	}
	log.Info().Msgf("container created: %s", resp.ID)
}
